package com.nstar.base.util
{
	import mx.controls.DataGrid;
	import flash.net.URLVariables;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.system.System;
	import flash.net.navigateToURL;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.external.ExternalInterface;
	
	public class ImpExpUtils
	{
		
		public function ImpExpUtils(){
			
		}
		
        /**
         * 将DataGrid表格中的数据输出到HTMLTable中
         * 调用这个方法后，可以将输出结果放到剪贴板里，然后通过调用javascript来打开Excel并粘贴进去
         * 		System.setClipboard(convertDGToHTMLTable(dg));
         * 		ExternalInterface.call("openExcel");//openExcel方法可见后面的注释部分
         * @param: dg 需要导出的DataGrid组件
         * @param: selected 为true时表示只导出每行数据中有checked属性且值为true的，false表示导出表格中所有的数据
         * @returns: 字符串
         */
        public function dataGrid2HTMLTable(dg:DataGrid,selected:Boolean=false):String {
        	//Set default values
        	var font:String = dg.getStyle('fontFamily');
        	var size:String = dg.getStyle('fontSize');
        	var str:String = '';
        	var colors:String = '';
        	var style:String = 'style="font-family:'+font+';font-size:'+size+'pt;"';				
        	var hcolor:Array;
        	
        	//Retrieve the headercolor
        	if(dg.getStyle("headerColor") != undefined) {
        		hcolor = [dg.getStyle("headerColor")];
        	} else {
        		hcolor = dg.getStyle("headerColors");
        	}				
        	
        	//Set the htmltabel based upon knowlegde from the datagrid
        	//str+= '<table width="'+dg.width+'"><thead><tr width="'+dg.width+'" style="background-color:#' +Number((hcolor[0])).toString(16)+'">';
        	//下面这个去掉了表格的头的背景设置
        	str+= '<table width="'+dg.width+'"><thead><tr width="'+dg.width+'" >';
        	
        	
        	//Set the tableheader data (retrieves information from the datagrid header				
        	for(var i:int = 0;i<dg.columns.length;i++) {
        		colors = dg.getStyle("themeColor");
        			
        		if(dg.columns[i].headerText != undefined) {
        			str+="<th "+style+">"+dg.columns[i].headerText+"</th>";
        		} else {
        			str+= "<th "+style+">"+dg.columns[i].dataField+"</th>";
        		}
        	}
        	str += "</tr></thead><tbody>";
        	colors = dg.getStyle("alternatingRowColors");
        	
        	//Loop through the records in the dataprovider and 
        	//insert the column information into the table
        	for(var j:int =0;j<dg.dataProvider.length;j++) {	
        		str+="<tr width=\""+Math.ceil(dg.width)+"\">";
        			
        		for(var k:int=0; k < dg.columns.length; k++) {
        			
        			//Do we still have a valid item?						
        			if(dg.dataProvider.getItemAt(j) != undefined && dg.dataProvider.getItemAt(j) != null) {
        				if (selected){
        					if (!dg.dataProvider.getItemAt(j).hasOwnProperty("checked")){
        						throw new Error("没有设置每行数据的checked属性值！");
        					}
        					if (dg.dataProvider.getItemAt(j).checked==false){
        						continue;
        					}
        				}
        				//Check to see if the user specified a labelfunction which we must
        				//use instead of the dataField
        				if(dg.columns[k].labelFunction != undefined) {
        					str += "<td width=\""+Math.ceil(dg.columns[k].width)+"\" "+style+">"+dg.columns[k].labelFunction(dg.dataProvider.getItemAt(j),dg.columns[k].dataField)+"</td>";
        					
        				} else {
        					//Our dataprovider contains the real data
        					//We need the column information (dataField)
        					//to specify which key to use.
        					str += "<td width=\""+Math.ceil(dg.columns[k].width)+"\" "+style+">"+dg.dataProvider.getItemAt(j)[dg.columns[k].dataField]+"</td>";
        				}
        			}
        		}
        		str += "</tr>";
        	}
        	str+="</tbody></table>";
        
        	return str;
        }
        
		/**
		 * Load a specific datagrid into Excel
		 * This method passes the htmltable string to an backend script which then
		 * offers the excel download to the user.
		 * The reason for not using a copy to clipboard and then javascript to
		 * insert it into Excel is that this mostly will fail because of the user
		 * setup (Webbrowser configuration).
		 * 
		 * @params: dg Datagrid The Datagrid that will be loaded into Excel
		 */
		public function loadDGInExcel(dg:DataGrid,expUrl:String="/yourpath/result.jsp"):void {

			//Pass the htmltable in a variable so that it can be delivered
			//to the backend script
			var variables:URLVariables = new URLVariables(); 
			variables.htmltable	= dataGrid2HTMLTable(dg);
			//Setup a new request and make sure that we are 
			//sending the data through a post
			var u:URLRequest = new URLRequest(expUrl);
			u.data = variables; //Pass the variables
			u.method = URLRequestMethod.POST; //Don't forget that we need to send as POST
			
			//Navigate to the script
			//We can use _self here, since the script will through a filedownload header
			//which results in offering a download to the user (and still remaining in you Flex app.)
            navigateToURL(u,"_self");
        }  
        
        //设置定时器，检查页面的初始化状态
        public function timerHandler(event:TimerEvent):void {
            var isReady:Boolean = checkJavaScriptReady();
            if (isReady) {
                Timer(event.target).stop();
            }
        }			
        //检查页面是否初始准备好
        public function checkJavaScriptReady():Boolean {
            var isReady:Boolean = ExternalInterface.call("isReady");
            return isReady;
        }
        
        //复制到剪贴板并打开Excel
        public function copyAndOpenExcel(grid:DataGrid,selected:Boolean=false):void{
        	if (ExternalInterface.available) {
	        	//先检查一下页面是否准备好
	        	if (checkJavaScriptReady()){
		        	System.setClipboard(dataGrid2HTMLTable(grid,selected));
		            ExternalInterface.call("openExcel");        	
	        	}
        	}
        }
		                
       /**
        下面是放在页面中的javascript方法
		<SCRIPT Language="JavaScript1.2">
	    
	      var jsReady = false;
	      //下面这个方法提供给在swf中调用，以检查页面是否初始化完成
	      function isReady() {
	          return jsReady;
	      }
	      //页面初始化参数，设置body的onLoad方法为此方法, <body onload="pageInit();">
	      function pageInit() {
	          jsReady = true;
	      }		
		
		
		var excel = null;
		function openExcel()
		{
			try
			{
		
				if(excel == null)
				{	
				 excel = new ActiveXObject("Excel.Application");
		
				}
				var workbook = excel.Workbooks.Add();
		
				workbook.Activate();
				var worksheet = workbook.Worksheets("Sheet1");
				worksheet.Activate();
		
				worksheet.Paste();
				excel.visible=true;
		
		
		
			}catch(exception)
			{
				window.alert("Now you may Paste into an Excel SpreadSheet");
			}
		}
		</SCRIPT>        
      */  		
	}
}